package com.bvbot.core.bot;

import static com.bvbot.core.Logger.log;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.bvbot.core.extractor.BvExtractor;
import com.bvbot.json.JsonTool;

public class PricesRecorder extends TimerTask {

	private static final long PERIOD = 10000L; // 1 min

	private static final long NB_ITERATIONS_BEFORE_DUMP = 8640L;

	private int iterationsNumber = 0;

	private final BvExtractor extractor = new BvExtractor();

	private final PricesHistory history = new PricesHistory();

	private static final SimpleDateFormat SDF = new SimpleDateFormat(
			"yyyy.MM.dd.HH.mm.ss");

	private static final String DUMP_FILE_PREFIX = "/PricesRecord-";
	private static final String DUMP_FILE_SUFFIX = ".dump";

	public PricesRecorder() {
		super();
	}

	@Override
	public void run() {
		iterationsNumber++;
		log("PricesRecorder : start of run");
		try {
			Prices p = extractor.extract();
			if (p != null) {
				history.addCurrentPrice(p);
			} else {
				log("extractor returns null !");
			}
			if (iterationsNumber >= NB_ITERATIONS_BEFORE_DUMP) {
				iterationsNumber = 0;
				try {
					String fileName = DUMP_FILE_PREFIX + SDF.format(new Date())
							+ DUMP_FILE_SUFFIX;
					log("Dumping prices in " + fileName);
					FileOutputStream fos = new FileOutputStream(fileName);
					byte[] bytes = JsonTool.get().toJson(history, true);
					fos.write(bytes);
					fos.flush();
					fos.close();
				} catch (Throwable e) {
					log("Exception : " + e.getMessage(), e);
				}
			}
		} catch (Throwable e) {
			log("Exception : " + e.getMessage(), e);
		}
		log("PricesRecorder : end of run");
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PricesRecorder r = new PricesRecorder();
		Timer t = new Timer();
		t.scheduleAtFixedRate(r, new Date(), PERIOD);
	}
}
